package com.zyw.zhuangdian.handler;

import com.zyw.zhuangdian.enums.MsgCode;
import com.zyw.zhuangdian.exceptions.MyDaoException;
import com.zyw.zhuangdian.exceptions.TokenInvalidException;
import com.zyw.zhuangdian.pojo.Resp;
import com.zyw.zhuangdian.util.RespUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class MyExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);

    /**
     * 处理数据库index重复异常
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public ResponseEntity handlerDuplicateKeyException(Exception e) {
        logger.error(e.getMessage());
        return RespUtil.SYSTEM_ERROR(new Resp(MsgCode.MSG_USER_EXISTED.getCode(), MsgCode.MSG_USER_EXISTED.getMsg(), null));
    }

    /**
     * 处理业务抛出异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity handlerIllegalArgumentException(Exception e) {
        logger.warn(e.getMessage());
        return RespUtil.SYSTEM_ERROR(new Resp(MsgCode.MSG_ILLEGAL_ARGUMENT.getCode(), MsgCode.MSG_ILLEGAL_ARGUMENT.getMsg(), e.getMessage()));
    }

    /**
     * 处理数据库抛出异常
     */
    @ExceptionHandler(MyDaoException.class)
    public ResponseEntity handlerMyDaoException(Exception e) {
        logger.warn(e.getMessage());
        return RespUtil.SYSTEM_ERROR(new Resp(MsgCode.MSG_DAO_ERROR.getCode(), MsgCode.MSG_DAO_ERROR.getMsg(), e.getMessage()));
    }

    /**
     * 处理token验证抛出异常
     */
    @ExceptionHandler(TokenInvalidException.class)
    public ResponseEntity handlerTokenInvalidException(TokenInvalidException e) {
        logger.warn(e.getMessage());
        return RespUtil.UN_AUTH(e.getMsg());
    }


}
